
#include "codec/pcm_codec.h"
#include "logger.h"

CPcmCodec::CPcmCodec()
{
}

CPcmCodec::~CPcmCodec()
{
}

NAudioFormats::ECodec CPcmCodec::getCodecType()
{
	return NAudioFormats::PCM;
}

double CPcmCodec::convertFromS8ToDouble(int8_t pSample)
{
	if(pSample == -128) {
		return -1.0;
	}
	return static_cast<double>(pSample) / 127.0;
}

int8_t CPcmCodec::convertFromDoubleToS8(double pSample)
{
	if(pSample > 1.0) {
		printl(LL_WARN, __FILE__, "Sample > 1.0 (%lf)", pSample);
		return 127;
	}
	if(pSample < -1.0) {
		printl(LL_WARN, __FILE__, "Sample < -1.0 (%lf)", pSample);
		return -128;
	}
	return static_cast<int8_t>(pSample * 127.0 + 0.5);
}

double CPcmCodec::convertFromU8ToDouble(uint8_t pSample)
{
	if(pSample == 0) {
		return -1;
	}
	return (static_cast<double>(pSample) - 128.0) / 127.0;
}

uint8_t CPcmCodec::convertFromDoubleToU8(double pSample)
{
	if(pSample > 1.0) {
		printl(LL_WARN, __FILE__, "Sample > 1.0 (%lf)", pSample);
		return 255;
	}
	if(pSample < -1.0) {
		printl(LL_WARN, __FILE__, "Sample < -1.0 (%lf)", pSample);
		return 0;
	}
	return static_cast<uint8_t>(pSample * 127.0 + 128.5);
}

double CPcmCodec::convertFromS16ToDouble(int16_t pSample)
{
	if(pSample == -32768) {
		return -1.0;
	}
	return static_cast<double>(pSample) / 32767.0;
}

int16_t CPcmCodec::convertFromDoubleToS16(double pSample)
{
	if(pSample > 1.0) {
		printl(LL_WARN, __FILE__, "Sample > 1.0 (%lf)", pSample);
		return 32767;
	}
	if(pSample < -1.0) {
		printl(LL_WARN, __FILE__, "Sample < -1.0 (%lf)", pSample);
		return -32768;
	}
	return static_cast<int16_t>(pSample * 32767.0 + 0.5);
}

double CPcmCodec::convertFromU16ToDouble(uint16_t pSample)
{
	if(pSample == 0) {
		return -1.0;
	}
	return (static_cast<double>(pSample) - 32768.0) / 32767.0;
}

uint16_t CPcmCodec::convertFromDoubleToU16(double pSample)
{
	if(pSample > 1.0) {
		printl(LL_WARN, __FILE__, "Sample > 1.0 (%lf)", pSample);
		return 32767;
	}
	if(pSample < -1.0) {
		printl(LL_WARN, __FILE__, "Sample < -1.0 (%lf)", pSample);
		return -32768;
	}
	return static_cast<uint16_t>(pSample * 32767.0 + 32768.5);
}
